package com.zys.el.search.dao.Impl;

import com.alibaba.fastjson.JSON;
import com.zys.el.search.aspect.AnticleAspect;
import com.zys.el.search.dao.AnticleDao;
import com.zys.el.search.po.Anticle;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Repository
public class AnticleDaoImpl implements AnticleDao {

    @Autowired
    private AnticleAspect aspect;

    @Override
    public boolean createIndex() throws IOException {
        RestHighLevelClient client = aspect.getClient();
        CreateIndexRequest request = new CreateIndexRequest("note_el");
        String json = "{\n" +
                "    \"properties\":{\n" +
                "      \"noteId\":{\n" +
                "        \"type\":\"keyword\"\n" +
                "      },\n" +
                "      \"authorId\":{\n" +
                "        \"type\":\"long\"\n" +
                "      },\n" +
                "      \"userName\":{\n" +
                "        \"type\":\"text\",\n" +
                "        \"analyzer\": \"ik_max_word\",\n" +
                "        \"search_analyzer\": \"ik_max_word\"\n" +
                "      },\n" +
                "      \"content\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"ik_max_word\",\n" +
                "        \"search_analyzer\": \"ik_max_word\",\n" +
                "        \"copy_to\": [\"all\"]\n" +
                "      },\n" +
                "      \"item\":{\n" +
                "        \"type\":\"text\",\n" +
                "        \"analyzer\": \"ik_max_word\",\n" +
                "        \"search_analyzer\": \"ik_max_word\",\n" +
                "        \"copy_to\": [\"all\"]\n" +
                "      },\n" +
                "      \"introduction\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"ik_max_word\",\n" +
                "        \"search_analyzer\": \"ik_max_word\",\n" +
                "        \"copy_to\": [\"all\"]\n" +
                "      },\n" +
                "      \"all\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"ik_max_word\",\n" +
                "        \"search_analyzer\": \"ik_max_word\"\n" +
                "      }\n" +
                "    }\n" +
                "  \n" +
                "}";
        System.out.println(json);
        request.source(json, XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);

        return false;
    }

    @Override
    public boolean addDoc(Anticle anticle) {

        RestHighLevelClient client = aspect.getClient();
        IndexRequest request = new IndexRequest("note_el").id(anticle.getNoteId().toString());
        String json = JSON.toJSONString(anticle);
        request.source(json, XContentType.JSON);
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public boolean addAllDoc(List<Anticle> list) throws IOException {
        RestHighLevelClient client = aspect.getClient();
        BulkRequest bulkRequest = new BulkRequest();

        for (Anticle anticle : list) {
            IndexRequest request = new IndexRequest("note_el").id(anticle.getNoteId().toString());
            String json = JSON.toJSONString(anticle);
            request.source(json, XContentType.JSON);
            bulkRequest.add(request);
        }

        client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return true;
    }

    @Override
    public Anticle getById(Long id) {
        GetRequest request = new GetRequest("note_el", id.toString());
        GetResponse response = null;
        RestHighLevelClient client = aspect.getClient();
        try {
            response = client.get(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String sourceAsString = response.getSourceAsString();
        Anticle anticle = JSON.parseObject(sourceAsString, Anticle.class);
        return anticle;
    }

    /**
     * 模糊搜索
     *
     * @param field         字段
     * @param searchRequest 内容
     * @return
     * @throws IOException
     */
    @Override
    public List<Anticle> search(String field, com.zys.el.search.po.SearchRequest searchRequest) throws IOException {

        RestHighLevelClient client = aspect.getClient();
        SearchRequest request = new SearchRequest("note_el");
        List<Anticle> list = new ArrayList<>();

        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.wildcardQuery(field, "*" + searchRequest.getKey() + "*"));// 查字段 查内容
        System.out.println(searchRequest.getPage() + ":" + searchRequest.getSize());
        builder.from(searchRequest.getPage()).size(searchRequest.getSize());
//        builder.sort("age", SortOrder.DESC);//排序字段
        request.source(builder);
        SearchHit[] hits = client.search(request, RequestOptions.DEFAULT).getHits().getHits();
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            Anticle anticle = JSON.parseObject(source, Anticle.class);
            list.add(anticle);
        }
        return list;
    }

    @Override
    public Boolean deleteDocById(Long id) {
        System.out.println("-----------------");
        RestHighLevelClient client = aspect.getClient();
        System.out.println("====================");
        DeleteRequest request = new DeleteRequest("note_el", id.toString());
        try {
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {

            e.printStackTrace();
            return false;
        }
        return true;
    }

}
